<template>
  <div id="container" :style="{ width: '190vh', height: '90vh' }">
  <input id="key-input" placeholder="请输入关键字"/>
  </div>
</template>
<script>
  export default{
    data() {
      return{
        map:''
      }
    },
    mounted(){
      // 初始化地图,初始化要放在$nextTick里面,一开始使用的话会找不到id="container"的DMO
      this.$nextTick(() => {
        this.init()
      })
    },
    methods:{
      init(){
        let that = this
        // 初始化
        this.map = new AMap.Map('container', {
          resizeEnable: true
        })
        // 输入框输入事件
        var autoOptions = {
          input: 'key-input'
        }
        var auto = new AMap.Autocomplete(autoOptions)
        var placeSearch = new AMap.PlaceSearch({
          map: that.map,
          extensions: 'all',
          children: 1
        })
        // 展示下拉选项
        AMap.event.addListener(auto, 'select', function(e) {
          placeSearch.setCity(e.poi.adcode)
          placeSearch.search(e.poi.name)
          let data = {
            poiAddress: e.poi.name,
            region: e.poi.adcode
          }
          that.mapData = data
        })
        // 地图鼠标点击事件
        this.map.on('click', (e) => {
          let lng = e.lnglat.lng
          let lat = e.lnglat.lat
          let marker = new AMap.Marker({
            position: new AMap.LngLat(lng, lat)
          })
          // 根据点击地图的经纬度获取地址详情
          //let geocoder = new AMap.Geocoder({ batch: false, city: '' })
          let geocoder
          AMap.plugin('AMap.Geocoder',function(){
            geocoder = new AMap.Geocoder()
          })
          geocoder.getAddress([lng, lat], function(status, res) {
            if (res.info == 'OK') {
              // 显示点标志的信息窗口
              let infoWindow = new AMap.InfoWindow({
                anchor: 'top-left',
                content: res.regeocode.formattedAddress
              })
              infoWindow.open(that.map, [lng, lat])
            }
          })
          that.map.clearMap()// 清除所有覆盖物（点标志）
          that.map.add(marker)// 添加点标志
        })
      }
    }
  }
</script>
